﻿using Newtonsoft.Json;
using SpaceNeedle.City6473.Web.Data.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace SpaceNeedle.City6473.WebSite.Security.Mvc
{
    public static class Auth
    {
        public static bool IsAdmin
        {
            get
            {
                var user = CurrentUser;
                return user != null && user.Roles == ConfigurationManager.AppSettings["adminRole"];
            }
        }

        public static UsersAuthentication CurrentUser
        {
            get
            {
                try
                {
                    if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                    {
                        string userData = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                        return JsonConvert.DeserializeObject<UsersAuthentication>(userData);
                    }
                }
                catch { }

                return null;
            }

            set
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        value.Email,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        false,
                        JsonConvert.SerializeObject(value),
                        FormsAuthentication.FormsCookiePath);

                //For security reasons we may hash the cookies
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                ////gera o cockie de autenticação
                FormsAuthentication.SetAuthCookie(value.Email, false);

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                //HttpContext.Current.User.Identity.IsAuthenticated
                // add the cookie to user browser
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        public static void SignOut()
        {
            try
            {
                FormsAuthentication.SignOut();

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
                cookie.Expires = DateTime.Now.AddYears(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch { }
        }
    }
}